package org.ricks.orm.mongodb.thread;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.WriteModel;
import org.bson.Document;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author ricks [chenwei]
 * @Version [v1.0]
 * @CreateTime 2024-06-12   11:57
 * @Description TODO
 */
public class DBThreadMrg extends Thread{

    //业务线程 actor 模式
    private Executor executor;

    private MongoCollection<Document> collection;

    /**
     * 这是一个db写线程作为生产者,主线程作为消费者的队列
     */
    private final LinkedBlockingQueue<Event> events = new LinkedBlockingQueue<>();

    @Override
    public void run() {
        while (true) {
            try {
                Event event = events.poll();
                executor.execute(() -> event.callBackHandler.callBack());
                assert event != null;
                collection.bulkWrite(List.of(event.getWriteModel()));
            } catch (Exception e) {

            }
        }
    }

    /**
     * 一个DB语句的事件
     */
    private abstract static class Event {
        private final long eventTime;
        private final DBCallBackHandler callBackHandler;
        private final String collectionName;

        public Event(String collectionName, long eventTime, DBCallBackHandler callBackHandler) {
            super();
            this.collectionName = collectionName;
            this.callBackHandler = callBackHandler;
            this.eventTime = eventTime;
        }

        public abstract WriteModel<Document> getWriteModel();
    }
}
